package UseMap.UseHashMap;

import java.util.*;

public class HashMapPractice {
    public static void main(String[] args) {
        // practice01();
        practice02();
    }
    // 练习1 添加学生的对象操作一下
    public static void practice01(){
        // 存储学生对象作为键，需要重写hashcode和equals方法
        HashMap<Student,String> map = new HashMap<>();
        Student s1 = new Student("小平",18);
        Student s2 = new Student("小绿",19);
        Student s3 = new Student("小红",20);
        map.put(s1,"程破屋");
        map.put(s2,"吴家干");
        map.put(s3,"洞嘎要");
        // 方式一：增强for
        System.out.println("-----增强for------");
        Set<Student> students = map.keySet();
        for (Student student : students) {
            System.out.println(student+"="+map.get(student));
        }
        // 方式二：entry对象
        System.out.println("-----entry对象------");
        Set<Map.Entry<Student, String>> entries = map.entrySet();
        for (Map.Entry<Student, String> entry : entries) {
            Student key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key+"="+value);
        }

        // 方式三：lambada
        System.out.println("-----lambada------");
        map.forEach((student,s)->{
            System.out.println(student+"="+s);
        });
    }

    // 练习2 统计同学选择景点的次数
    public static void practice02(){
        // 准备数据
        String[] arr = {"A","B","C","D"};
        Random random = new Random();
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < 80; i++) {
            int index = random.nextInt(arr.length);
            list.add(arr[index]);
        }
        // 获取各种各种选择的数据
        HashMap<String,Integer> hm = new HashMap<>();
        for (String name : list) {
            // 已经存在数据了
            if(hm.containsKey(name)){
                int count = hm.get(name);
                count++;
                hm.put(name,count);
            }else{
                hm.put(name,1);
            }
        }
        System.out.println(hm);
        // 求选择最大次数
        int max = 0;
        Set<Map.Entry<String, Integer>> entries = hm.entrySet();
        for (Map.Entry<String, Integer> entry : entries) {
            int count = entry.getValue();
            if(count > max){
                max = count;
            }
        }
        // 获取值的操作
        System.out.println(max);
        for (Map.Entry<String, Integer> entry : entries) {
            int count = entry.getValue();
            if(max == count){
                System.out.println(entry.getKey());
            }
        }
    }
}
